package com.lovezy.platform.play.service.impl;

import com.github.pagehelper.Page;
import com.lovezy.platform.core.base.enums.StatusEnum;
import com.lovezy.platform.core.base.query.Pager;
import com.lovezy.platform.core.base.service.MapperService;
import com.lovezy.platform.core.exception.ServiceException;
import com.lovezy.platform.filestore.service.FileHelper;
import com.lovezy.platform.play.mapper.PlayAttachmentMapper;
import com.lovezy.platform.play.model.PlayAttachment;
import com.lovezy.platform.play.model.PlayAttachmentExample;
import com.lovezy.platform.play.query.PlayQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

import static com.lovezy.platform.core.utils.ObjectUtil.nonNull;

/**
 * Created by jin on 2018/2/3.
 */
@Service
public class PlayAttachmentService extends MapperService<PlayAttachment, Integer, PlayAttachmentMapper> {

    @Autowired
    FileHelper fileHelper;

    public PlayAttachment newAttachment(PlayAttachment attachment) {
        attachment.setAttachmentId(null);
        attachment.setStatus(StatusEnum.NORMAL.value());
        attachment.setGmtCreate(new Date());
        mapper.insert(attachment);
        return attachment;
    }

    public Page<PlayAttachment> findAttachments(PlayQuery query) {
        Integer playId = query.getPlayId();
        nonNull(playId);

        PlayAttachmentExample example = new PlayAttachmentExample();
        example.createCriteria()
                .andPlayIdEqualTo(playId)
                .andStatusEqualTo(StatusEnum.NORMAL.value());
        Page<PlayAttachment> attachments = Pager.doPage(query, () -> mapper.selectByExample(example));
        attachments.stream()
                .filter(a -> a.getFileKey() != null)
                .forEach(a -> {
                    a.setFileKey(fileHelper.toDownloadUrl(a.getFileKey()));
                });
        return attachments;
    }

    public void deleteAttachment(PlayAttachment attachment) {
        PlayAttachment deleteAtt = new PlayAttachment();
        Integer attachmentId = attachment.getAttachmentId();
        deleteAtt.setAttachmentId(attachmentId);
        deleteAtt.setStatus(StatusEnum.DELETED.value());
        mapper.updateByPrimaryKeySelective(deleteAtt);
    }

    public void editAttachment(PlayAttachment attachment) {
        Integer attachmentId = attachment.getAttachmentId();
        nonNull(attachmentId);
        PlayAttachment playAttachment = mapper.selectByPrimaryKey(attachmentId);
        if (playAttachment == null) {
            throw new ServiceException("附件不存在");
        }

        mapper.updateByPrimaryKeySelective(attachment);
    }

}
